package com.zrf.testchatgpt.shiro.realm;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zrf.testchatgpt.entity.Permission;
import com.zrf.testchatgpt.entity.Role;
import com.zrf.testchatgpt.entity.Users;
import com.zrf.testchatgpt.shiro.SerializableByteSource;
import com.zrf.testchatgpt.shiro.token.LoginToken;
import com.zrf.testchatgpt.mapper.PermissionMapper;
import com.zrf.testchatgpt.mapper.RoleMapper;
import com.zrf.testchatgpt.mapper.UsersMapper;
import com.zrf.testchatgpt.shiro.util.JwtTokenUtil;
import com.zrf.testchatgpt.util.RedisCacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;
import java.util.stream.Collectors;

//@Component
@Slf4j
public class LoginRealm extends AuthorizingRealm {
    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Autowired
    RedisCacheUtil redisCacheUtil;
    @Autowired
    UsersMapper usersMapper;

    @Autowired
    RoleMapper roleMapper;
    @Autowired
    PermissionMapper permissionMapper;
    @Override
    public String getName() {
        return "LoginRealm";
    }

    /*
     * 多重写一个support
     * 标识这个Realm是专门用来验证LoginToken
     * 不负责验证其他的token（UsernamePasswordToken）
     * */
    @Override
    public boolean supports(AuthenticationToken token) {
        //这个token就是从过滤器中传入的jwtToken
        return token instanceof LoginToken;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Users user = (Users) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        List<Role> roles = roleMapper.queryByUserId(user.getId());
        List<Permission> permissions = permissionMapper.queryByRoleId(user.getId());
        if (!roles.isEmpty()){

            roles.forEach(role -> {log.info("角色："+role.getRoleName());info.addRole(role.getRoleName());});
        }

        if(!permissions.isEmpty()){
            Set<String> permsSet = permissions.stream()
                    .map(Permission::getSn)
                    .filter(Objects::nonNull)
                    .flatMap(s -> Arrays.stream(s.split(",")))
                    .collect(Collectors.toSet());
//        for (Permission perm : permissions) {
//            log.info("授权："+perm.getSn());
//            permsSet.addAll(Arrays.asList(perm.getSn().trim().split(",")));
//        }
            info.setStringPermissions(permsSet);
        }
//        Set<String> roleSet=new HashSet<>();
//        for (Role perm : roles) {
//            permsSet.addAll(Arrays.asList(perm.getRoleName().trim().split(",")));
//        }

        return info;
    }

    //认证
    //这个token就是从过滤器中传入的jwtToken
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        LoginToken loginToken = (LoginToken) token;
//        //获取用户输入的用户名密码
//        String wxName = loginToken.getWxName();
//        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        LambdaQueryWrapper<Users> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Users::getWxName,loginToken.getWxName());
        Users users = usersMapper.selectOne(wrapper);
        System.out.println("用户输入--->wxName:"+users.getWxName()+"-->openid:"+users.getUserOpenid());
        return new SimpleAuthenticationInfo(users, users.getUserOpenid(), new SerializableByteSource("koorye_love_md5"), getName());
    }

}
